import 'package:badges/badges.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_demo/controllers/article_detail_controller.dart';
import 'package:flutter_demo/controllers/fav_list_controller.dart';
import 'package:flutter_demo/controllers/user_controller.dart';
import 'package:flutter_demo/pages/login_page.dart';
import 'package:flutter_demo/pages/web_page.dart';
import 'package:flutter_demo/utils/const.dart';
import 'package:flutter_demo/views/image_preview.dart';
import 'package:flutter_demo/views/loading_container.dart';
import 'package:flutter_demo/views/video_view.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:get/get.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';
import 'package:url_launcher/url_launcher_string.dart';
// import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';

import '../entities/article_detail.dart';
import '../entities/article_item.dart';

class ArticleDetailPage extends GetWidget<ArticleDetailController> {
  ArticleDetailPage({Key? key}) : super(key: key) {
    Get.create(() => ArticleDetailController());
  }

  @override
  Widget build(BuildContext context) {
    final articleItem = Get.arguments;
    Get.log("$articleItem");
    return Scaffold(
      bottomNavigationBar: _buildBottomBar(),
      appBar: AppBar(
        title: Obx(() => Text(controller.detail.value.title)),
        actions: [
          GetBuilder<FavListController>(
            init: FavListController(),
            builder: (favC) => GestureDetector(
              onTap: () => favC.isFav(articleItem) ? favC.removeFav(articleItem) : favC.addFav(articleItem),
              child: Icon(
                favC.isFav(articleItem) ? Icons.favorite : Icons.favorite_border_outlined,
                color: Colors.redAccent,
              ),
            ).paddingOnly(right: 13),
          ),
        ],
        elevation: 0,
        toolbarHeight: Const.kAppBarHeight,
      ),
      body: Obx(
        () => LoadingContainer(
          status: controller.detailLoadingStatus.value,
          child: ScrollablePositionedList.separated(
            physics: const BouncingScrollPhysics(),
            itemScrollController: controller.scrollController,
            padding: const EdgeInsets.all(5),
            itemBuilder: (context, index) {
              if (index == 0) {
                return _buildContent();
              } else if (index == controller.detail.value.comments.length + 1) {
                return _buildHots();
              } else {
                final comment = controller.detail.value.comments[index - 1];
                return _buildComment(comment);
              }
            },
            separatorBuilder: (context, index) {
              return const Divider(height: 0.5);
            },
            itemCount: controller.detail.value.comments.length + 2,
          ),
        ),
      ),
    );
  }

  Widget _buildContent() {
    var detail = controller.detail.value;
    var sections = List<Widget>.empty(growable: true);
    sections.add(
      Padding(
        padding: const EdgeInsets.fromLTRB(0, 5, 0, 10),
        child: Text(
          detail.title,
          style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
        ),
      ),
    );
    if (detail.tags != null) {
      sections.add(
        Padding(
          padding: const EdgeInsets.only(bottom: 5),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: detail.tags
                .map(
                  (e) => Row(
                    children: [
                      ClipOval(
                        child: Container(
                          color: Colors.green,
                          width: 6,
                          height: 6,
                        ),
                      ).marginOnly(right: 3),
                      Text(
                        e,
                        style: const TextStyle(fontSize: 12),
                        overflow: TextOverflow.clip,
                      ).paddingOnly(right: 10),
                    ],
                  ),
                )
                .toList(),
          ),
        ),
      );
    }
    sections.addAll(detail.items.map((item) => _buildItem(item)));
    if (detail.items.isNotEmpty) {
      sections.add(Padding(
        padding: const EdgeInsets.only(top: 10, bottom: 10),
        child: Row(
          children: [
            Container(
              width: 4,
              height: 15,
              color: Get.theme.primaryColor,
            ),
            Padding(
              padding: const EdgeInsets.only(left: 5),
              child: Text(
                "评论（${detail.comments.length}）",
                style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
            ),
          ],
        ),
      ));
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: sections,
    );
  }

  Widget _buildComment(Comment comment) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ClipOval(
          child: CachedNetworkImage(
            width: 36,
            height: 36,
            imageUrl: comment.avatar,
            httpHeaders: Const.imgHeaders,
            fit: BoxFit.cover,
          ),
        ).paddingOnly(right: 5),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  comment.isVip
                      ? const Icon(
                          Icons.emoji_events,
                          color: Colors.orange,
                          size: 16,
                        )
                      : Container(),
                  Text(
                    comment.nickname,
                    style: TextStyle(color: comment.isVip ? Colors.orange : Colors.green),
                  ),
                ],
              ),
              Text(comment.createTime, style: const TextStyle(color: Colors.black38, fontSize: 12))
                  .paddingOnly(top: 3, bottom: 3),
              Text(
                comment.content,
                style: const TextStyle(fontSize: 13, color: Colors.black87),
              ),
            ],
          ),
        )
      ],
    ).paddingAll(8);
  }

  Widget _buildHots() {
    var detail = controller.detail.value;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Container(
              width: 4,
              height: 15,
              color: Get.theme.primaryColor,
            ),
            const Padding(
              padding: EdgeInsets.fromLTRB(5, 10, 5, 10),
              child: Text(
                "热门推荐",
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
            ),
          ],
        ),
        GridView(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2, mainAxisSpacing: 8, childAspectRatio: 1.06, crossAxisSpacing: 10.0),
          children: detail.hots.map((e) => _buildArticleItem(e)).toList(),
        ),
      ],
    );
  }

  Widget _buildItem(Item item) {
    if (item.type == "img") {
      return Padding(
        padding: const EdgeInsets.only(bottom: 10),
        child: InkWell(
          onTap: () => _handleShowPreview(item),
          child: CachedNetworkImage(
            imageUrl: item.content!,
            httpHeaders: Const.imgHeaders,
          ),
        ),
      );
    } else if (item.type == "video") {
      return VideoView(
        url: item.content!,
      );
    }
    return Html(
      data: item.content!,
      onLinkTap: (url, a, b, c) {
        if (url?.startsWith("https://fourpetal.com/") == true) {
          final articleItem = ArticleItem();
          articleItem.title = c!.text.toString();
          articleItem.link = url.toString();
          _handleToDetail(articleItem);
        } else if (url != null) {
          _handleToDownloadPage(url);
        }
        Get.log("$url, $a, $b, $c");
      },
    );
  }

  Widget _buildArticleItem(ArticleItem item) {
    return InkWell(
      onTap: () => _handleToDetail(item),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          AspectRatio(
            aspectRatio: 208 / 117,
            child: CachedNetworkImage(
              imageUrl: item.cover.toString(),
              httpHeaders: Const.imgHeaders,
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(bottom: 10, top: 5),
            child: Text(
              item.title.toString(),
              style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
              maxLines: 2,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBottomBar() {
    return Container(
      height: 50,
      color: Colors.blue,
      child: Row(
        children: [
          Expanded(
            child: InkWell(
              onTap: _handleComment,
              child: Container(
                padding: const EdgeInsets.fromLTRB(20, 8, 10, 8),
                child: Text(
                  "发表评论~",
                  style: TextStyle(color: Get.theme.primaryColor),
                ),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(20),
                ),
              ),
            ).paddingOnly(left: 10, right: 10),
          ),
          InkWell(
            child: Badge(
              badgeContent: Obx(() => Text(
                    controller.detail.value.comments.length.toString(),
                    style: const TextStyle(color: Colors.white, fontSize: 10),
                  )),
              child: const Icon(
                Icons.comment,
                color: Colors.white,
              ).paddingOnly(right: 10),
            ).paddingOnly(right: 15),
            onTap: () => controller.scrollToComment(),
          ),
          Container(
            color: Colors.redAccent,
            height: 50,
            child: InkWell(
              child: const Padding(
                padding: EdgeInsets.only(left: 40, right: 40, top: 15),
                child: Text(
                  "下载",
                  style: TextStyle(color: Colors.white),
                ),
              ),
              onTap: _handleDownload,
            ),
          )
        ],
      ),
    );
  }

  // 显示图片预览
  _handleShowPreview(Item item) {
    final List<Item> items = controller.detail.value.items.where((element) => element.type == 'img').toList();
    final index = items.indexOf(item);
    Get.dialog(ImagePreview(list: items.map((e) => e.content!).toList(), index: index, onClose: () => Get.back()),
        barrierDismissible: true, barrierColor: Colors.black);
  }

  // 评论
  _handleComment() {
    final userController = Get.find<UserController>();
    if (!userController.isLogin()) {
      Get.to(() => LoginPage());
    }
  }

  // 下载
  _handleDownload() {
    Get.bottomSheet(
      SizedBox(
        child: Column(
          children: [
            const Padding(
              padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
              child: Text(
                "资源选择",
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
            ),
            const Divider(
              height: 0.0,
              indent: 0.0,
              color: Colors.black26,
            ),
            Expanded(
              child: Obx(
                () => LoadingContainer(
                    status: controller.linkLoadingStatus.value,
                    child: DefaultTabController(
                      length: 2,
                      child: Column(
                        children: [
                          TabBar(
                            padding: EdgeInsets.zero,
                            indicatorSize: TabBarIndicatorSize.label,
                            indicatorWeight: 3,
                            labelColor: Get.theme.primaryColor,
                            tabs: const [
                              Tab(
                                text: "解析链接",
                                height: 36,
                              ),
                              Tab(
                                text: "原链接",
                                height: 36,
                              )
                            ],
                          ),
                          const Divider(
                            height: 0.5,
                          ),
                          Expanded(
                            child: TabBarView(
                              children: [
                                ListView(
                                  children: controller.links
                                      .map(
                                        (link) => Column(children: [
                                          ListTile(
                                            title: Text(link.title),
                                            horizontalTitleGap: 0,
                                            subtitle: link.desc == null ? null : Text(link.desc!),
                                            leading: const Icon(Icons.plagiarism_sharp),
                                            trailing: const Icon(Icons.keyboard_arrow_right_sharp),
                                            onTap: () => _handleToDownloadPage(link.href),
                                          ),
                                          const Divider(
                                            height: 0.5,
                                          ),
                                        ]),
                                      )
                                      .toList(),
                                ),
                                ListView(children: [
                                  Html(
                                    data: controller.linkHtml.value,
                                    onLinkTap: (url, a, b, c) {
                                      if (url?.startsWith("https://fourpetal.com/") == true) {
                                        final articleItem = ArticleItem();
                                        articleItem.title = c!.text.toString();
                                        articleItem.link = url.toString();
                                        _handleToDetail(articleItem);
                                      } else if (url != null) {
                                        _handleToDownloadPage(url);
                                      }
                                      Get.log("$url, $a, $b, $c");
                                    },
                                  ),
                                ]),
                              ],
                            ),
                          ),
                        ],
                      ),
                    )),
              ),
            ),
          ],
        ),
        height: 400,
      ),
      backgroundColor: Colors.white,
    );
  }

  // 跳转下载页
  _handleToDownloadPage(String href) {
    if (GetUtils.hasMatch(href, r"^((?!baidu|quark|aliyun|sharepoint).)*$")) {
      launchUrlString(href, mode: LaunchMode.externalApplication);
    } else {
      Get.to(() => WebPage(), arguments: href);
    }
  }

  // 跳转详情页
  _handleToDetail(ArticleItem item) {
    Get.to(() => ArticleDetailPage(), arguments: item, preventDuplicates: false);
  }
}
